package com.zhoust.design.strategy.config;

import com.zhoust.design.strategy.annotation.PayCodeAnnotation;
import com.zhoust.design.strategy.context.PayStrategyContext;
import com.zhoust.design.strategy.intf.PayStrategy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhoushengtao
 * @version v1.0
 * @date 2021/11/1 21:45
 * @desc 从上下文中获取所有 PayCodeAnnotation 注解的对象，并放入context 的map中
 */
@Configuration
public class CreateStrategyMapConfig {

    private final ApplicationContext context;

    public CreateStrategyMapConfig(ApplicationContext context) {
        this.context = context;
    }
    @Bean
    public PayStrategyContext getPayStrategyContext(PayStrategyContext payStrategyContext){
        ConcurrentHashMap<String, PayStrategy> strategyMap = new ConcurrentHashMap<String, PayStrategy>();
        // 从上下文中拿到带注解PayCodeAnnotation的对象
        Map<String, Object> payStrategyAnnotations = context.getBeansWithAnnotation(PayCodeAnnotation.class);

        for (String key :payStrategyAnnotations.keySet()) {
            // 获取对象
            PayStrategy payStrategy = (PayStrategy) payStrategyAnnotations.get(key);
            // 获取注解对应的 payCode
            String payCode = payStrategy.getClass().getAnnotation(PayCodeAnnotation.class).payCode();
            // 放入map中
            strategyMap.put(payCode,payStrategy);
        }
        payStrategyContext.setStrategyMap(strategyMap);
        return payStrategyContext;
    }
}
